import { ref } from "vue"
import type { TableInstance } from 'element-plus'
import { download } from '@/utils/index'
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { getToken } from "@/utils/cache/cookies"

const useTable = (props: any)=> {
  const tableRef = ref<TableInstance>()
  const multipleSelection = ref<any[]>([])
  const { getList } = props
  const statusLoading = ref(0)
  const activeRow = ref<any>()

  const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
  }

  const changeIsEnable = (api: any, id: number, params:any = {}) => {
    statusLoading.value = id
    api({id:id,...params}).then(() => {
    }).finally(() => {
      statusLoading.value = 0
    })
  }

  //批量删除
  const handleBatchDelete = (api: any, key: string) => {
    if(!multipleSelection.value.length) {
      ElMessage.warning("请选择要删除的项")
      return
    }
    ElMessageBox.confirm(`是否确认删除选中项？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      api({ids:multipleSelection.value.map((item)=>{
        return item[key]
      })}).then(() => {
        ElMessage.success("删除成功")
        getList()
      })
    })
  }

  //删除
  const handleDelete = (api: any, id:string|number, title:string) => {
    ElMessageBox.confirm(`正在删除：${title}，确认删除？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      api({ids:[id]}).then(() => {
        ElMessage.success("删除成功")
        getList()
      })
    })
  }
  // 单个删除
  const handleoneDelete = (api: any, id:string|number, title:string) => {
    ElMessageBox.confirm(`正在删除：${title}，确认删除？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      api({id:id}).then(() => {
        ElMessage.success("删除成功")
        getList()
      })
    })
  }


    //批量重置密码
    const handleBatchResetPW = (api: any, key: string) => {
      if(!multipleSelection.value.length) {
        ElMessage.warning("请选择要重置密码的项")
        return
      }
      ElMessageBox.confirm(`是否确认重置密码选中项？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        api({ids:multipleSelection.value.map((item)=>{
          return item[key]
        })}).then(() => {
          ElMessage.success("删除成功")
          getList()
        })
      })
    }
  
    //删除
    const handleResetPW = (api: any, id:string|number, title:string) => {
      ElMessageBox.confirm(`正在重置密码：${title}，确认重置？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        api({ids:[id]}).then(() => {
          ElMessage.success("删除成功")
          getList()
        })
      })
    }




  //批量上下架
  const handleStatusBatch = (api: any, status: number, key: string, propKey: string) => {
    if(!multipleSelection.value.length) {
      ElMessage.warning(`请选择要${!status ? '下架' : '上架'}的项`)
      return
    }
    ElMessageBox.confirm(`是否确认批量${!status ? '下架' : '上架'}？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      const params:any = {status:status}
      params[propKey] = multipleSelection.value.map((item)=>{
        return item[key]
      })
      api(params).then(() => {
        ElMessage.success("删除成功")
        getList()
      })
    })
  }

  //导出
  const handleExport = async (params: any, api: any,name:string) => {
    const baseUrl = import.meta.env.MODE === 'development' ? '/api' : '';
    const token = getToken();
    const apiUrl = baseUrl + api;
    console.log(apiUrl);
    fetch(apiUrl,{
      method: "POST",
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
        "Content-Type": "application/json",
        "token": token
      },
      body:JSON.stringify(params),
      responseType: 'blob'
    }).then(res => {     
      return res.blob();
    }).then(blob => {
      console.log(blob,'blob')
      let bl = new Blob([blob], {type:'application/vnd.ms-excel,charset=utf-8' });
      // let fileName =name?name:'文件名'+".xlsx";
      let fileName =`${name?name:'文件名'}.xlsx`;
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      window.URL.revokeObjectURL(link.href);
    })

    // api(params).then((res: any)=>{
    //   download(res,'导出结果')
    // })
  }

  return {
    multipleSelection,
    handleSelectionChange,
    tableRef,
    handleBatchDelete,
    handleDelete,
    handleoneDelete,
    changeIsEnable,
    statusLoading,
    handleStatusBatch,
    handleExport,
    activeRow,
    handleBatchResetPW,
    handleResetPW
  }
}

export default useTable
